package hp.com.servlet.OrderServlet;

import hp.com.entity.CartData;
import hp.com.entity.Orders;
import hp.com.entity.Users;
import hp.com.service.CartDataService;
import hp.com.service.OrderService;
import hp.com.service.impl.CartDataServiceImpl;
import hp.com.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/PlaceOrder")
public class DoAddOrder extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        OrderService os = new OrderServiceImpl();
        String cartId=req.getParameter("cart");
        String addId = req.getParameter("addr");
        HttpSession session = req.getSession();
        Users user =(Users)req.getSession().getAttribute("userSession");
        Orders order =null;
        try{order=os.getOrderBySerial(os.DoInsertOrder(cartId,addId,user));}catch (Exception e){
            e.printStackTrace();
        };
        CartDataService cds = new CartDataServiceImpl();
        String[] carts = cartId.split(",");
        for (int i = 0; i < carts.length; i++) {
            try{cds.DeleteCartData(Integer.parseInt(carts[i]));}catch (Exception e){
                e.printStackTrace();
            }
        }
        req.setAttribute("order",order);
        req.setAttribute("userSession",session.getAttribute("userSession"));
        req.getRequestDispatcher(req.getContextPath()+"/ShopPage/paymentSuccess.jsp").forward(req,resp);
    }
}
